<script lang="ts" setup>

import { onMounted, reactive, ref, toRef, toRefs, watch, watchEffect } from 'vue'
import type { PageInfo, Result } from '@/tools/request'
import type { SysMenu } from '@/api/system/sysMenu/sysMenu.d'
import { sysMenuList } from '@/api/system/sysMenu/sysMenu'
import type { TableRowSelection } from '@arco-design/web-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  selectKeys: {
    type: Array,
    required: true,
    default: () => []
  }
})

const selectKeysRef = ref([...props.selectKeys])
watch(() => props.selectKeys, (newVal) => {
  selectKeysRef.value = newVal
})

const emits = defineEmits(['update:visible', 'commit'])
const closeModal = () => {
  emits('update:visible', false)
}

//加载列表
const loadList = () => {
  //@ts-ignore
  sysMenuList({} as SysMenu, { pageSize: 99999999999, pageNum: 1 }).then((resp: Result<PageInfo<SysMenu>>) => {
    const map = new Map()
    resp.data.list.forEach(v => {
      map.set(v.id, v)
    })
    resp.data.list.forEach(v => {
      if (v.parentId) {
        if (!map.get(v.parentId)['children']) {
          map.get(v.parentId)['children'] = []
        }
        map.get(v.parentId)['children'].push(v)
      }
    })
    resp.data.list = []
    map.forEach((value) => {
      if (!value.parentId) {
        resp.data.list.push(value)
      }
    })

    table.menusMap = map
    table.pageInfo = resp.data
  })
}
loadList()

const table = reactive({
  pageInfo: { list: [] as Array<SysMenu> } as PageInfo<SysMenu>,
  menusMap: null as Map<number, SysMenu> | null,
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    checkStrictly: true
  } as TableRowSelection,
  columns: [{
    title: 'ID',
    dataIndex: 'id'
  }, {
    title: '菜单名',
    dataIndex: 'menuName'
  }, {
    title: '路由地址',
    dataIndex: 'url'
  }],
  selectChange: (keys: string[]) => {
    table.checkMenus = keys.map(val => table.menusMap!.get(Number(val)) as SysMenu)
  },
  checkMenus: [] as SysMenu[],
  submit: () => {
    emits('commit', table.checkMenus)
    emits('update:visible', false)
  }
})


</script>

<template>
  <a-modal @cancel="closeModal" :visible="visible" title="选择菜单" title-align="start" :closable="false"
           :footer="null" :width="1000">
    <a-space class="mb-2">
      <a-button type="primary" @click="table.submit">
        <template #icon>
          <IconSave />
        </template>
        提交
      </a-button>
      <a-button @click="closeModal">
        <template #icon>
          <IconExport />
        </template>
        取消
      </a-button>
    </a-space>
    <a-table v-model:selected-keys="selectKeysRef" row-key="id" :row-selection="table.rowSelection"
             :data="table.pageInfo!.list" :columns="table.columns" @selectionChange="table.selectChange" />

  </a-modal>
</template>

<style scoped lang="scss">

</style>
